package com.jyw.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import com.jyw.common.annotation.Log;
import com.jyw.common.config.RuoYiConfig;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.entity.SysDept;
import com.jyw.common.core.domain.entity.SysUser;
import com.jyw.common.core.domain.model.LoginUser;
import com.jyw.common.enums.BusinessType;
import com.jyw.common.utils.SecurityUtils;
import com.jyw.common.utils.StringUtils;
import com.jyw.common.utils.file.FileUploadUtils;
import com.jyw.common.utils.file.MimeTypeUtils;
import com.jyw.framework.web.service.SysPermissionService;
import com.jyw.framework.web.service.TokenService;
import com.jyw.system.domain.dto.UpdatePwdDto;
import com.jyw.system.domain.vo.UserDeptRoleVO;
import com.jyw.system.domain.vo.UserInfoVo;
import com.jyw.system.service.ISysDeptService;
import com.jyw.system.service.ISysUserDeptRoleService;
import com.jyw.system.service.ISysUserService;
import com.jyw.system.service.ISysUserTeamService;
import com.jyw.system.utils.TeamUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 个人信息 业务处理
 * 
 * @author system
 */
@RestController
@RequestMapping("/system/user/profile")
@Api(tags = "个人信息")
public class SysProfileController extends BaseController
{
    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    @Resource
    private ISysUserDeptRoleService deptRoleService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ISysDeptService iSysDeptService;

    @Resource
    private ISysUserTeamService userTeamService;

    /**
     * 个人信息
     */
    @GetMapping
    public CommonResult<LoginUser> profile()
    {
        LoginUser loginUser = getLoginUser();
        return CommonResult.success(loginUser);
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getUser();
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        user.setAvatar(null);
//        user.setDeptId(null);
        if (userService.updateUserProfile(user) > 0)
        {
            // 更新缓存用户信息
            sysUser.setNickName(user.getNickName());
            sysUser.setPhonenumber(user.getPhonenumber());
            sysUser.setEmail(user.getEmail());
            sysUser.setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

//    /**
//     * 修改用户
//     */
//    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
//    @PutMapping("role/{id}")
//    @ApiOperation("修改部门角色")
//    public CommonResult updateUserDeptRole(@PathVariable Long id)
//    {
//        SysUserDeptRole deptRole = deptRoleService.getById(id);
//        if(ObjectUtils.isEmpty(deptRole)){
//            throw new ServiceException("用户角色不存在");
//        }
//        if(!deptRole.getUserId().equals(SecurityUtils.getUserId())){
//            throw new ServiceException("不存在该角色权限");
//        }
//        LoginUser loginUser = SecurityUtils.resetUserDeptRole(deptRole.getDeptId(), deptRole.getRoleId(), deptRole.getId());
//        loginUser.setPermissions(permissionService.getMenuPermission(SecurityUtils.getLoginUser().getUser(), deptRole));
//
//
//        tokenService.setLoginUser(loginUser);
//
//
//        return CommonResult.success();
//    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    @ApiOperation("修改密码")
    public CommonResult updatePwd(@RequestBody @Valid UpdatePwdDto pwdDto)
    {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(pwdDto.getOldPassword(), password))
        {
            return CommonResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(pwdDto.getNewPassword(), password))
        {
            return CommonResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(pwdDto.getNewPassword())) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(pwdDto.getNewPassword()));
            tokenService.setLoginUser(loginUser);
            return CommonResult.success();
        }
        return CommonResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("登录用户信息")
    public CommonResult<UserInfoVo> getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(user);
        // 获取部门角色对象
//        SysUserDeptRole userDeptRole = deptRoleService.getById(SecurityUtils.getLoginUser().getUserDeptRoleId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user, SecurityUtils.getLoginUser().getSysRoleList());
//        user.setRoleId(SecurityUtils.getLoginUser().getRoleId());
        user.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        SysDept sysDept=iSysDeptService.selectDeptById(SecurityUtils.getLoginUser().getDeptId());
        if(sysDept!=null){
            user.setDeptId(sysDept.getDeptId());
            user.setDeptName(sysDept.getDeptName());
        }
        if(CollUtil.isNotEmpty(permissions)){
            user.setPermissions(permissions);
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUser(user);
        //查询用户所属小组
        List<Long> teamIds = userTeamService.getTeamIdByUser(SecurityUtils.getUserId());
        userInfoVo.setTeams(TeamUtils.cacheList().stream().filter(data->teamIds.contains(data.getId())).collect(Collectors.toList()));

        return CommonResult.success(userInfoVo);
    }


    /**
     * 用户拥有的部门角色信息
     *
     * @return 用户信息
     */
    @GetMapping("dept/role")
    @ApiOperation("用户拥有的部门角色信息")
    public CommonResult<List<UserDeptRoleVO>> getUserDeptRoleInfo()
    {
        return CommonResult.success(deptRoleService.getUserDeptRoleInfo());
    }


    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
